package com.zc.bigdata.yarn.v1;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.File;
import java.io.IOException;

/**
 * 访问流量统计
 */
public class FlowAPP {

    public static void main(String[] args) throws Exception {
        System.setProperty("hadoop.home.dir","D://gitee//hadoop-2.6.0");
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);

        job.setJarByClass(FlowAPP.class);
        job.setMapperClass(MyMapper.class);
        job.setReducerClass(MyReducer.class);

        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(LongWritable.class);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(LongWritable.class);

        // 提前删除输入目录，以免运行报错
        FileUtils.deleteDirectory(new File("output//tracklog//flow"));

        // 设置输入文件夹和输出文件夹
        FileInputFormat.setInputPaths(job,new Path("input//tracklog//"));
        FileOutputFormat.setOutputPath(job,new Path("output//tracklog//flow"));

        // 执行job
        boolean result = job.waitForCompletion(true);
        System.out.println(result);

    }

    static class MyMapper extends Mapper<LongWritable, Text, NullWritable, LongWritable> {

        private LongWritable ONE = new LongWritable(1);

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            context.write(NullWritable.get(), ONE);
        }
    }

    static class MyReducer extends Reducer<NullWritable, LongWritable, NullWritable, LongWritable> {
        @Override
        protected void reduce(NullWritable key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0L;
            for (LongWritable value : values) {
                sum+=value.get();
            }
            context.write(NullWritable.get(),new LongWritable(sum));
        }
    }

}
